<template>
  <div>
    <h1>购物车</h1>
    <el-table :data="cartItems" style="width: 100%">
      <el-table-column prop="productName" label="商品名称"></el-table-column>
      <el-table-column prop="quantity" label="数量"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="viewProduct(scope.row.productId)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-button type="primary" @click="checkout">结算</el-button>
  </div>
</template>

<script>
import { getCartItems } from '@/api/cart';
import { createOrder } from '@/api/order';

export default {
  data() {
    return {
      cartItems: [],
    };
  },
  methods: {
    async fetchCartItems() {
      const response = await getCartItems(this.$store.state.userId);
      this.cartItems = response.data;
    },
    viewProduct(productId) {
      this.$router.push({ path: `/products/${productId}` });
    },
    async checkout() {
      const orderData = {
        items: this.cartItems.map(item => ({
          productId: item.productId,
          quantity: item.quantity,
        })),
      };
      await createOrder(orderData);
      this.$message.success('订单创建成功！');
      this.fetchCartItems();
    },
  },
  mounted() {
    this.fetchCartItems();
  },
};
</script>

<style scoped>
.cart {
  padding: 20px;
}
</style>